// M.doSql=M.Db().doSql
let Db=M.Db()

app.begin(req=>{
  //  console.log("app.begin",req.pureUrl,req.params)
})

app.get("/miApiListByPage",function (req,res) {
    let whereCase="1=1 ";
    if(req.params.name){
        whereCase=whereCase+` and name like '%${req.params.name}%'`
    }
    if(req.params.parent_id){
        whereCase=whereCase+` and parent_id = '${req.params.parent_id}'`
    }
    const sql1=` 
    select * from mi_api  where ${whereCase}  limit  ${(req.params.startPage-1)*req.params.limit},${req.params.limit}`
   const sql2= `
        select count(1) c from mi_api  where ${whereCase};
    `;
    M.doSql(sql1).then((d) => {
        let rows = d;
        M.doSql(sql2).then((d) => {
            let total = d[0].c; 
            res.send({rows ,total});
        });
    })
});

s="\"{\"url\":\"https://naikim.coding.io/\",\"method\":\"post\",\"headers\":{\"Content-Type\":\"application/x-www-form-urlencoded\"},\"data\":{\"sql\":\"select * from mi_log\"}}\""
app.post("/miApiAdd",async function (req,res) {
    let miApi=req.params;
    delete miApi.id;
    miApi.leaf=1;
    if(!miApi.parent_id){
        miApi.parent_id=-1;
    }
    miApi.gmt_create=new Date().getTime();
    miApi.gmt_modified=new Date().getTime();
    let sql = Db.getInsertObjSql("mi_api",miApi) + ";";
    M.doSql(sql).then(d=>{
        M.doSql(Db.getUpdateObjSql("mi_api",{leaf:0},{id:miApi.parent_id})).then(e=>  res.send("ok"))
    })
});

app.post("/miApiUpdate",function (req,res) {
    let miApi=req.params;
    let sql =Db.getUpdateObjSql("mi_api",miApi) + ";";
    M.doSql(sql).then(d=>{
        res.send("ok");
    })
});


app.get("/miApiDelete",async function (req,res) {
    let id=req.params.id;
     let sql=`
                delete from 
                mi_api
                WHERE 
                id
                in
                (
                    select id from (
                    select t1.id,
                    if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild
                    from (
                            select id,parent_id from mi_api t   order by parent_id, id
                            ) t1,
                            (select @pids := ${id}) t2
                    ) t3 where ischild != 0
                    union
                    SELECT ${id} from DUAL
                )
     `;
    M.doSql(sql).then(async d=>{
         res.send("ok");
    })
});


app.get("/miApiDeleteAll",function (req,res) {
    let sql=`DELETE from mi_api where 1=1`
    M.doSql(sql).then(d=>{
         res.send("ok")
    })
});

app.get("/miApiSetStatus",function (req,res) {
    let sql=`update mi_api set status='${req.params.status}' where id=${req.params.id};`
    M.doSql(sql).then(d=>{
        res.send("ok");
    })
});


M.log=function(d){
    let sql=`insert into mi_log (content) values('${d}');`
    M.doSql(sql).then(d=>{})
}



